package com.appspot.zarm.gomoku;

import com.appspot.zarm.game.Player;
import com.appspot.zarm.game.PlayerType;
import com.appspot.zarm.gomoku.validation.Evaluator;
import com.appspot.zarm.gomoku.validation.Validator;
import com.appspot.zarm.transfer.GameState;

public class GomokuGameFacade {

	private GomokuGame game;
	private Player player;
	private Player rival;

	public GomokuGameFacade(GomokuGame game, Player player) {
		this.game = game;
		this.player = player;
		this.rival = game.getRival(player);
	}

	public void doTurn(Coord position) {
		Cell cell = game.getBoard().getCell(position);
		// player`s turn
		if (game.isThisPlayerTurn(player)) {
			
			// validate
			if (new Validator().validateEmpty(cell)) {
				
				if (player.getType() == PlayerType.ONE) {
					cell.setCellState(CellState.CROSS);
				} else {
					cell.setCellState(CellState.ZERO);
				}
				
				// evaluate
				if (new Evaluator().evaluate(game, player.getType())) {
					game.setState(GameState.PLAYER_WINS);
					return;
				}
				
				game.setThisPlayerTurn(rival);
			}
		}
		
		// rival`s turn
		if (rival != null && rival.isRobot() && game.isThisPlayerTurn(rival)) {

			position = game.getRobot().doTurn(game.getBoard());

			if (position != null) {
				cell = game.getBoard().getCell(position);

				// validate
				if (new Validator().validateEmpty(cell)) {
					
					if (rival.getType() == PlayerType.ONE) {
						cell.setCellState(CellState.CROSS);
					} else {
						cell.setCellState(CellState.ZERO);
					}
					
					// evaluate
					if (new Evaluator().evaluate(game, rival.getType())) {
						game.setState(GameState.COMPUTER_WINS);
						return;
					}
					game.setThisPlayerTurn(player);
				}
			}
		}
	}

	public void finish() {
		
	}

	public void start() {
	}

}
